<template>
  <div class="navbar">
    <hamburger id="hamburger-container" :is-active="sidebar.opened" class="hamburger-container"
               @toggleClick="toggleSideBar"/>
    <breadcrumb id="breadcrumb-container" class="breadcrumb-container"/>
    <div class="right-menu">

      <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click">
        <el-badge :max="99" :value="notReadNum" class="item">
          <el-button size="mini" type="primary" icon="el-icon-message-solid"></el-button>
          <i class="el-icon-caret-bottom"></i>
        </el-badge>

        <el-dropdown-menu slot="dropdown">
<!--          <el-dropdown-item>
            <el-badge :max="99" :value="notReadNum" class="item">
              <div style="padding: 0 10px" @click="drawerOpen">消息</div>
            </el-badge>
          </el-dropdown-item>-->
          <el-dropdown-item>
            <el-badge :max="99" :value="notReadNum" class="item">
              <div style="padding: 0 10px" @click="drawerOpen">新增订单消息</div>
            </el-badge>
          </el-dropdown-item>

            <el-dropdown-item>
              <el-badge :max="99" :value="notReadNum" class="item">
                <div style="padding: 0 10px" @click="drawerOpen">订单采购通知</div>
              </el-badge>
            </el-dropdown-item>

            <el-dropdown-item>
              <el-badge :max="99" :value="notReadNum" class="item">
                <div style="padding: 0 10px" @click="drawerOpen">订单生产消息</div>
              </el-badge>
            </el-dropdown-item>
          <el-dropdown-item>
            <el-badge :max="99" :value="notReadNum" class="item">
              <div style="padding: 0 10px" @click="drawerOpen">入库消息</div>
            </el-badge>
          </el-dropdown-item>
          <el-dropdown-item>
            <el-badge :max="99" :value="notReadNum" class="item">
              <div style="padding: 0 10px" @click="drawerOpen">出库消息</div>
            </el-badge>
          </el-dropdown-item>
          <el-dropdown-item>
            <el-badge :max="99" :value="notReadNum" class="item">
              <div style="padding: 0 10px" @click="drawerOpen">财务审核询价通知</div>
            </el-badge>
          </el-dropdown-item>
          <el-dropdown-item>
            <el-badge :max="99" :value="notReadNum" class="item">
              <div style="padding: 0 10px" @click="drawerOpen">订单质检通知</div>
            </el-badge>
          </el-dropdown-item>
          <el-dropdown-item>
            <el-badge :max="99" :value="notReadNum" class="item">
              <div style="padding: 0 10px" @click="drawerOpen">取消订单消息</div>
            </el-badge>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <a style="vertical-align: 16px;margin-right: 30px;">嗨，{{ realName }}</a>

      <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click">
        <div class="avatar-wrapper">
          <img src="https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80" alt="头像"
               class="user-avatar">
          <i class="el-icon-caret-bottom"></i>
        </div>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item>
            <router-link to="/">首页</router-link>
          </el-dropdown-item>
          <el-dropdown-item divided>
            <span style="display:block;" @click="openChangePassDialog">修改密码</span>
          </el-dropdown-item>
          <el-dropdown-item divided>
            <span style="display:block;" @click="logout">退出</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>


    </div>
    <el-drawer
      :with-header="false"
      :visible.sync="drawer"
      size="40%"
    >
      <div><b>消息中心 </b>
        <div style="display: inline-block;width: 55%">
          <el-input style="margin-left: 5%; width: 200px" size="mini"  v-model="searchKeywords" placeholder="请输入搜索关键字" clearable > </el-input>
          <el-button   type="primary" size="mini"  style="margin-left: 5%;" @click="searchKeywordsFun" >查询</el-button>
        </div>
        <el-popconfirm
          confirm-button-text='确定'
          cancel-button-text='取消'
          icon="el-icon-info"
          icon-color="red"
          title="确认标记所有消息为已读吗？"
          @confirm="readAllOrderMessageByUserId"
        >

          <el-button size="mini" plain style="margin-left: 5%" slot="reference" >全部标为已读</el-button>


        </el-popconfirm>

        <span title="关闭" @click="drawer=false">
          <i class="el-dialog__close el-icon el-icon-close" title="关闭" style="float: right;cursor: pointer"></i>
        </span>
      </div>
      <el-divider></el-divider>
      <div class="sdk-menus-drawer__body">
        <div class="qc-nav-message-list" style="height: 760px">

          <template v-for="message in messages">
            <div class="qc-nav-message-inner" :key="message.id">
              <div class="qc-nav-message-div">
                <span class="qc-nav-message-text">{{ message.title }}</span>
                <span class="qc-nav-message-time">{{ message.createTime }}</span>
              </div>
              <div class="qc-message-dd" style="padding: 10px 0;position: relative">
                <div style="display: flex">
                  <div style="flex: 4">
                    <a href="#">{{ message.messageInfo }}</a>
                  </div>
                  <div style="flex: 1" v-if="message.hasRead === 0">
                    <el-tooltip class="item" effect="dark" content="确认消息已读" placement="bottom" :hide-after="1800"
                                :open-delay="800">
                      <el-button type="success" size="small" icon="el-icon-message" @click="confirmMessage(message)"
                                 circle></el-button>
                    </el-tooltip>
                  </div>
                </div>
              </div>
            </div>
          </template>

          <el-pagination
            background
            style="margin-top: 20px;text-align: center;"
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="pageIndex"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            :total="totalCount">
          </el-pagination>
        </div>

      </div>
    </el-drawer>
    <el-dialog title="修改密码" :visible.sync="changePasswordDialogVis" width="30%">
      <normal-form
        ref="dataForm"
        :dataForm="dataForm"
        :config="dataFormConfig"
        :dataRule="getNeedDataRule('password', 'confirmPassword')"
        :showLabel="true"
        :showAll="true"
        :submitFunc="dialogCommitHandler"
      ></normal-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changePasswordDialogVis = false">取 消</el-button>
        <el-button type="primary" @click="dialogCommitHandler">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import Breadcrumb from '@/components/Breadcrumb'
import Hamburger from '@/components/Hamburger'
import {clearLoginInfo} from '@/utils'
import {mRequest} from '@/utils/request'
import dialogMixins from '@/utils/commonDialogMixins'
import normalForm from '@/components/normalForm/form'

export default {
  mixins: [dialogMixins],
  components: {
    Breadcrumb,
    Hamburger,
    normalForm
  },
  computed: {
    ...mapGetters([
      'sidebar'
    ]),
    realName() {
      return this.$cookie.get('realName')
    }
  },
  data() {
    return {
      searchKeywords: '',
      messageType: '',
      notReadNum: 0,
      dataForm: {
        password: '',
        confirmPassword: ''
      },
      dataFormConfig: {
        password: {
          label: '密码',
          inputType: 'password',
          placeholder: '请输入密码'
        },
        confirmPassword: {
          label: '确认密码',
          inputType: 'password',
          placeholder: '确认密码'
        }
      },
      messages: [],
      changePasswordDialogVis: false,
      pageIndex: 1,
      totalCount: 0,
      pageSize: 10,
      drawer: false,
      direction: 'rtl'
    }
  },
  methods: {
    confirmMessage(message) {
      message.hasRead = 1

      mRequest('orderApi/updateOrderMessage', message, ({data}) => {
        if (this.R.equals(0, data.code)) {
          this.unreadCountGet()
          this.orderListQuery()
        }
      })
    },
    createSocket(userId, userToken) {
      const socketPath = `ws://127.0.0.1:13333/deviShop/websocket/${userId}?token=${userToken}`
      console.log('socket==>' + socketPath)
      const ws = new WebSocket(socketPath)
      console.info('正在建立连接')

      ws.onopen = () => {
        console.info('连接已建立')
      }
      ws.onmessage = (evt) => {
        const data = evt.data

        this.$notify({
          title: '收到新的消息',
          message: data,
          type: 'success',
          duration: 0
        })
        this.unreadCountGet()

        this.$vBus.$emit('WEBSOCKET_RECEIVE', data)
      }
      ws.onclose = function (e) {
        ws.close()
        console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean) // 打印断开原因
      }
    },
    dialogCommitHandler() {
      this.$refs.dataForm.validate((valid) => {
        if (!valid) {
          return
        }
        const option = {
          userId: this.$cookie.get('userId'),
          password: this.dataForm['password']
        }

        mRequest('systemApi/updatePassword', option, ({data}) => {
          if (this.R.equals(0, data.code)) {
            this.$message({
              message: '密码修改成功，请重新登入',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.changePasswordDialogVis = false
                this.$cookie.set('token', '')
                this.$router.push({name: 'login'})
              }
            })
          }
        })
      })
    },
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.orderListQuery()
    },
    currentChangeHandle(val) {
      this.pageIndex = val
      this.orderListQuery()
    },
    orderListQuery() {
      const params = {
        page: this.pageIndex,
        limit: this.pageSize,
        messageType: this.messageType,
        searchKeywords: this.searchKeywords
      }

      mRequest('orderApi/listOrderMessage', params, ({data}) => {
        if (data && data.code === 0) {
          const page = data.page

          this.totalCount = page.totalCount
          this.pageSize = page.pageSize
          this.messages = page.list

          const MESSAGE_TITLE = {
            0: '产品订单',
            1: '模具订单',
            2: '打样订单',
            3: '退货订单'
          }

          this.messages.forEach(item => {
            item.title = MESSAGE_TITLE[item.messageType]
          })
        }
      })
    },
    drawerOpen() {
      this.drawer = true
      this.orderListQuery()
    },
    toggleSideBar() {
      this.$store.dispatch('toggleSideBar')
    },
    logout() {
      this.$confirm('确定进行[退出]操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        mRequest('loginApi/logout', {}, ({data}) => {
          if (data && data.code === 0) {
            clearLoginInfo()
            this.$router.push({name: 'login'})
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(() => {
        this.$message.error('请联系管理员')
      })
    },
    openChangePassDialog() {
      this.changePasswordDialogVis = true
    },
    unreadCountGet() {
      this.notReadNum = 0

      mRequest('orderApi/getUnreadMessageCount', {}, ({data}) => {
        this.notReadNum += data.unreadCount
      })
    },
    searchKeywordsFun() {
      this.drawerOpen()
    },
    readAllOrderMessageByUserId() {
      mRequest('orderApi/readAllOrderMessageByUserId', {}, ({}) => {
        this.orderListQuery()

        this.unreadCountGet()
      })
    },
  },
  mounted() {
    this.$nextTick(() => {
      const token = this.$cookie.get('token')
      const userId = this.$cookie.get('userId')

      this.createSocket(userId, token)
      this.unreadCountGet()
    })
  }
}
</script>

<style lang="scss" scoped>
.navbar {
  height: 50px;
  overflow: hidden;
  position: relative;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, .08);

  .hamburger-container {
    line-height: 46px;
    height: 100%;
    float: left;
    cursor: pointer;
    transition: background .3s;
    -webkit-tap-highlight-color: transparent;

    &:hover {
      background: rgba(0, 0, 0, .025)
    }
  }

  .breadcrumb-container {
    float: left;
  }

  .errLog-container {
    display: inline-block;
    vertical-align: top;
  }

  .right-menu {
    float: right;
    height: 100%;
    line-height: 50px;

    .item {
      vertical-align: 15px;
      margin-right: 10px;
    }

    .el-badge {
      ::v-deep {
        .el-badge__content {
          margin-top: 8px
        }
      }

    }

    &:focus {
      outline: none;
    }

    .right-menu-item {
      display: inline-block;
      padding: 0 8px;
      height: 100%;
      font-size: 18px;
      color: #5a5e66;
      vertical-align: text-bottom;

      &.hover-effect {
        cursor: pointer;
        transition: background .3s;

        &:hover {
          background: rgba(0, 0, 0, .025)
        }
      }
    }

    .avatar-container {
      margin-right: 30px;

      .avatar-wrapper {
        margin-top: 5px;
        position: relative;

        .user-avatar {
          cursor: pointer;
          width: 40px;
          height: 40px;
          border-radius: 10px;
        }

        .el-icon-caret-bottom {
          cursor: pointer;
          position: absolute;
          right: -20px;
          top: 25px;
          font-size: 12px;
        }
      }
    }
  }
}

::v-deep .el-drawer__body {
  flex: 1 1 auto;
  overflow: auto;
  padding: 20px;

  .qc-nav-message-list {
    margin-top: -20px;

    .qc-nav-message-inner {
      padding: 15px 0 7px;
      position: relative;
      border-bottom: 1px solid #ddd;
      cursor: pointer;

      .qc-nav-message-div {
        line-height: 20px;
        color: #888;
        font-size: 12px;

        display:flow-root
        .qc-nav-message-text {
          float: left;
          width: 120px;
          overflow: hidden;
          text-overflow: ellipsis;
          vertical-align: middle;
          white-space: nowrap;
        }

        .qc-nav-message-time {
          float: right;
        }
      }

      .qc-message-dd a {
        color: #000;
        padding: 4px 0 0;
        line-height: 21px;
        max-height: 21px;
     /*   display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;*/
        overflow: hidden;
        font-size: 12px;
      }
    }
  }

}

</style>
